package com.dpj.fork_join_test;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

@Slf4j(topic = "c.TestForkJoin")
public class TestForkJoin {
    public static void main(String[] args) {
        ForkJoinPool pool= new ForkJoinPool(4);
        System.out.println(pool.invoke(new MyTask(5)));
        //new MyTask(5)   5+new MyTask(4)    3+new MyTask(2)    2+new MyTask(1)

    }
}
// the sum between 1~n
class MyTask extends RecursiveTask<Integer> {
    private  int n;
    public MyTask(int n){
        this.n=n;
    }


    @Override
    protected Integer compute() {
        if(n==1){
            return 1;
        }
        MyTask t1 = new MyTask(n - 1);
        t1.fork(); //let one thread to execute the task
        int result=n+t1.join(); //get the result
        return result;
    }
}
